<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Product extends Backend
{

    /**
     * Product模型对象
     * @var \app\admin\model\Product
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        
        // 获取当前操作方法
        $action = $this->request->action();
        
        // 如果是分类相关操作，不初始化商品模型
        if (in_array($action, ['category', 'categoryadd', 'categoryedit', 'categorydel'])) {
            return;
        }
        
        // 禁用数据权限限制，商品审核不需要按管理员权限限制
        $this->dataLimit = false;
        
        // 只在非Ajax请求且非index方法时初始化模型和设置视图变量
        if (!$this->request->isAjax() && $action !== 'index') {
            $this->model = new \app\admin\model\Product;
            $this->view->assign("auditStatusList", $this->model->getAuditStatusList());
            $this->view->assign("shelfStatusList", $this->model->getShelfStatusList());
        } else {
            // 对于Ajax请求和index方法，只初始化模型，不设置视图变量
            $this->model = new \app\admin\model\Product;
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自定义
     * 如果需要自定义，请复制对应的方法至此文件中
     */
     
    /**
     * 查看商品详情
     * 
     * @param int $ids 商品ID
     * @return string
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取商品分类信息
        $category = Db::name('product_category')->where('id', $row['category_id'])->find();
        $row['category_name'] = $category ? $category['name'] : '-';
        
        // 获取商家信息
        $merchant = Db::name('merchant_audit')->where('merchant_id', $row['merchant_id'])->find();
        $row['merchant_name'] = $merchant ? $merchant['store_name'] : '-';
        
        // 处理商品主图
        $mainImages = [];
        if ($row['main_image']) {
            $imageUrl = $row['main_image'];
            if (strpos($imageUrl, 'http') !== 0 && strpos($imageUrl, '//') !== 0) {
                $imageUrl = request()->domain() . $imageUrl;
            }
            $mainImages[] = ['image_url' => $imageUrl];
        }
        
        // 处理商品详情图片
        $detailImages = [];
        if ($row['images']) {
            $imageList = explode(',', $row['images']);
            foreach ($imageList as $image) {
                if ($image) {
                    $imageUrl = $image;
                    if (strpos($imageUrl, 'http') !== 0 && strpos($imageUrl, '//') !== 0) {
                        $imageUrl = request()->domain() . $imageUrl;
                    }
                    $detailImages[] = ['image_url' => $imageUrl];
                }
            }
        }
        
        // 获取商品规格信息
        $skus = Db::name('product_sku')->where('product_id', $ids)->select();
        
        // 获取商品属性价格信息
        $attributePrices = Db::name('product_attribute_price')
            ->where('product_id', $ids)
            ->select();
            
        // 将属性价格信息关联到SKU数据
        foreach ($skus as $key => $sku) {
            // 默认值
            $skus[$key]['market_price'] = 0.00;  // 权益商品价格
            $skus[$key]['original_price'] = 0.00; // 积分商品价格
            
            // 查找对应的属性价格记录
            foreach ($attributePrices as $price) {
                if ($price['sku_id'] == $sku['id']) {
                    // 根据attribute_type区分不同类型的价格
                    // 1=权益商品，2=积分商品
                    if ($price['attribute_type'] == 1) {
                        $skus[$key]['market_price'] = $price['price'];
                    } else if ($price['attribute_type'] == 2) {
                        $skus[$key]['original_price'] = $price['points'];
                    }
                }
            }
        }
        
        // 处理日期格式
        $row['createtime'] = date('Y-m-d H:i:s', $row['createtime']);
        $row['updatetime'] = date('Y-m-d H:i:s', $row['updatetime']);
        
        $this->view->assign("row", $row);
        $this->view->assign("mainImages", $mainImages);
        $this->view->assign("detailImages", $detailImages);
        $this->view->assign("skus", $skus);
        
        return $this->view->fetch();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            // 获取查询参数
            $auditStatus = $this->request->get('audit_status', 1);
            $shelfStatus = $this->request->get('shelf_status', '');
            $categoryId = $this->request->get('category_id', '');
            $merchantId = $this->request->get('merchant_id', '');
            
            // 构建查询条件
            $where = [];
            
            // 审核状态筛选
            if ($auditStatus !== '') {
                $where['audit_status'] = intval($auditStatus);
            }
            
            // 上架状态筛选
            if ($shelfStatus !== '') {
                $where['shelf_status'] = intval($shelfStatus);
            }
            
            // 分类筛选
            if ($categoryId !== '') {
                $where['category_id'] = intval($categoryId);
            }
            
            // 商家筛选
            if ($merchantId !== '') {
                $where['merchant_id'] = intval($merchantId);
            }
            
            // 获取分页参数
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            
            // 查询总数
            $total = Db::name('product')->where($where)->count();
            
            // 查询数据
            $list = Db::name('product')
                ->alias('p')
                ->join('product_category c', 'p.category_id = c.id', 'LEFT')
                ->join('merchant_audit m', 'p.merchant_id = m.merchant_id', 'LEFT')
                ->field('p.*, m.store_name as merchant_name, c.name as category_name')
                ->where($where)
                ->order('p.id', 'desc')
                ->page($page, $limit)
                ->select();
           
            // 处理商品图片和状态文本
            foreach ($list as &$row) {
                // 处理main_image字段，确保图片路径正确
                if (isset($row['main_image']) && $row['main_image']) {
                    // 检查是否为相对路径，如果是则添加域名
                    if (strpos($row['main_image'], 'http') !== 0 && strpos($row['main_image'], '//') !== 0) {
                        $row['main_image'] = request()->domain() . $row['main_image'];
                    }
                }
                
                // 处理image_list字段（如果需要）
                if (isset($row['images']) && $row['images']) {
                    $row['image_list'] = explode(',', $row['images']);
                } else {
                    $row['image_list'] = [];
                }
                
                // 处理审核状态文本
                $auditStatusMap = [
                    0 => '审核未通过',
                    1 => '审核通过', 
                    2 => '待审核'
                ];
                $row['audit_status_text'] = isset($auditStatusMap[$row['audit_status']]) ? $auditStatusMap[$row['audit_status']] : '未知';
                
                // 处理上下架状态文本
                $shelfStatusMap = [
                    0 => '下架',
                    1 => '上架'
                ];
                $row['shelf_status_text'] = isset($shelfStatusMap[$row['shelf_status']]) ? $shelfStatusMap[$row['shelf_status']] : '未知';
            }
            
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加商品属性价格配置
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 验证必要参数
                if (empty($params['product_id'])) {
                    $this->error('商品ID不能为空');
                }
                
                // 检查商品是否存在
                $product = Db::name('product')->where('id', $params['product_id'])->find();
                if (!$product) {
                    $this->error('商品不存在');
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $attributeData = [];
                    $productId = $params['product_id'];
                    
                    // 权益商品
                    if (isset($params['enable_equity']) && $params['enable_equity'] == 1 && isset($params['equity_price'])) {
                        $attributeData[] = [
                            'product_id' => $productId,
                            'attribute_type' => 1, // 权益商品
                            'price' => $params['equity_price'],
                            'points' => 0,
                            'is_default' => 0,
                            'status' => isset($params['shelf_status']) ? $params['shelf_status'] : 1,
                            'createtime' => time(),
                            'updatetime' => time()
                        ];
                    }
                    
                    // 积分商品
                    if (isset($params['enable_points']) && $params['enable_points'] == 1 && isset($params['points_price'])) {
                        $attributeData[] = [
                            'product_id' => $productId,
                            'attribute_type' => 2, // 积分商品
                            'price' => $params['points_price'],
                            'points' => isset($params['points']) ? $params['points'] : 0,
                            'is_default' => 0,
                            'status' => isset($params['shelf_status']) ? $params['shelf_status'] : 1,
                            'createtime' => time(),
                            'updatetime' => time()
                        ];
                    }
                    
                    // 助农商品
                    if (isset($params['enable_agriculture']) && $params['enable_agriculture'] == 1 && isset($params['agriculture_price'])) {
                        $attributeData[] = [
                            'product_id' => $productId,
                            'attribute_type' => 3, // 助农商品
                            'price' => $params['agriculture_price'],
                            'points' => 0,
                            'is_default' => 0,
                            'status' => isset($params['shelf_status']) ? $params['shelf_status'] : 1,
                            'createtime' => time(),
                            'updatetime' => time()
                        ];
                    }
                    
                    // 检查是否有属性数据需要插入
                    if (empty($attributeData)) {
                        $this->error('请至少选择一种商品属性类型并设置价格');
                    }
                    
                    // 批量插入属性价格数据
                    $result = Db::name('product_attribute_price')->insertAll($attributeData);
                    
                    Db::commit();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error('数据库错误：' . $e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('操作失败：' . $e->getMessage());
                }
                
                if ($result !== false) {
                    $this->success('商品属性价格配置添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('参数不能为空');
        }
        
        // 获取商品列表用于下拉选择
        $productList = Db::name('product')->where('audit_status', 1)->field('id,name')->order('id', 'desc')->select();
        $this->view->assign("productList", $productList);
        
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 如果没有设置主图片，使用第一张商品图片作为主图片
                if (empty($params['main_image']) && !empty($params['images'])) {
                    $imageArray = explode(',', $params['images']);
                    if (!empty($imageArray[0])) {
                        $params['main_image'] = trim($imageArray[0]);
                    }
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    
                    // 处理商品属性价格配置
                    if ($result) {
                        // 删除原有的属性价格配置
                        $attributePriceModel = new \app\admin\model\ProductAttributePrice;
                        $attributePriceModel->where('product_id', $ids)->delete();
                        
                        $attributeData = [];
                        
                        // 权益商品
                         if (isset($params['enable_equity']) && $params['enable_equity'] == 1 && isset($params['equity_price'])) {
                             $attributeData[] = [
                                 'product_id' => $ids,
                                 'attribute_type' => 1, // 权益商品
                                 'price' => $params['equity_price'],
                                 'points' => 0,
                                 'is_default' => 0,
                                 'status' => 1,
                                 'createtime' => time(),
                                 'updatetime' => time()
                             ];
                         }
                         
                         // 积分商品
                         if (isset($params['enable_points']) && $params['enable_points'] == 1 && isset($params['points_price'])) {
                             $attributeData[] = [
                                 'product_id' => $ids,
                                 'attribute_type' => 2, // 积分商品
                                 'price' => $params['points_price'],
                                 'points' => isset($params['points']) ? $params['points'] : 0,
                                 'is_default' => 0,
                                 'status' => 1,
                                 'createtime' => time(),
                                 'updatetime' => time()
                             ];
                         }
                         
                         // 助农商品
                         if (isset($params['enable_agriculture']) && $params['enable_agriculture'] == 1 && isset($params['agriculture_price'])) {
                             $attributeData[] = [
                                 'product_id' => $ids,
                                 'attribute_type' => 3, // 助农商品
                                 'price' => $params['agriculture_price'],
                                 'points' => 0,
                                 'is_default' => 0,
                                 'status' => 1,
                                 'createtime' => time(),
                                 'updatetime' => time()
                             ];
                         }
                         
                         // 批量插入属性价格数据
                         if (!empty($attributeData)) {
                             $attributePriceModel->saveAll($attributeData);
                         }
                    }
                    
                    // 处理商品图片
                    if (isset($params['images']) && !empty($params['images'])) {
                        // 删除原有的商品图片
                        $imageModel = new \app\admin\model\ProductImage;
                        $imageModel->where('product_id', $ids)->delete();
                        
                        // 保存新的商品图片
                        $imageArray = explode(',', $params['images']);
                        foreach ($imageArray as $index => $image) {
                            if (!empty(trim($image))) {
                                $imageModel->save([
                                    'product_id' => $ids,
                                    'image_url' => trim($image),
                                    'image_type' => 1, // 商品图片
                                    'sort' => $index,
                                    'createtime' => time()
                                ]);
                            }
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取分类列表用于下拉选择
        $categoryModel = new \app\admin\model\ProductCategory;
        $categoryList = $categoryModel->where('status', 1)->order('sort', 'asc')->select();
        $this->view->assign("categoryList", $categoryList);
        
        // 获取商品属性价格配置
        $attributePriceModel = new \app\admin\model\ProductAttributePrice;
        $attributePrices = $attributePriceModel->where('product_id', $ids)->select();
        
        // 处理属性价格数据，方便前端使用
        $row = $row->toArray();
        $row['enable_equity'] = 0;
        $row['enable_points'] = 0;
        $row['enable_agriculture'] = 0;
        $row['equity_price'] = '';
        $row['points_price'] = '';
        $row['agriculture_price'] = '';
        $row['points'] = '';
        
        // 确保必要字段存在，避免模板报错
        if (!isset($row['main_image'])) {
            $row['main_image'] = '';
        }
        if (!isset($row['description'])) {
            $row['description'] = '';
        }
        if (!isset($row['stock'])) {
            $row['stock'] = 0;
        }
        if (!isset($row['shelf_status'])) {
            $row['shelf_status'] = 0;
        }
        
        foreach ($attributePrices as $price) {
            switch ($price['attribute_type']) {
                case 1: // 权益商品
                    $row['enable_equity'] = 1;
                    $row['equity_price'] = $price['price'];
                    break;
                case 2: // 积分商品
                    $row['enable_points'] = 1;
                    $row['points_price'] = $price['price'];
                    $row['points'] = $price['points'];
                    break;
                case 3: // 助农商品
                    $row['enable_agriculture'] = 1;
                    $row['agriculture_price'] = $price['price'];
                    break;
            }
        }
        
        // 处理images字段，确保是字符串格式
        if (isset($row['images']) && is_array($row['images'])) {
            $row['images'] = implode(',', $row['images']);
        } elseif (!isset($row['images'])) {
            $row['images'] = ''; // 确保images字段存在，避免模板报错
        }
        
        // 从商品图片表获取图片数据
        $imageModel = new \app\admin\model\ProductImage;
        $productImages = $imageModel->where('product_id', $ids)->order('sort', 'asc')->select();
        if (!empty($productImages)) {
            $imageUrls = [];
            foreach ($productImages as $img) {
                $imageUrls[] = $img['image_url'];
            }
            $row['images'] = implode(',', $imageUrls);
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 权益商品列表
     */
    public function equity()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            try {
                // 获取请求参数
                $page = $this->request->get('page', 1);
                $limit = $this->request->get('limit', 10);
                $search = $this->request->get('search', '');
                
                // 计算偏移量
                $offset = ($page - 1) * $limit;
                
                // 构建查询条件 - 只查询权益商品 (attribute_type=1)
                $where = ['attribute_type' => 1];
                
                // 如果有搜索条件，需要关联商品表进行搜索
                $query = Db::name('product_attribute_price')
                    ->alias('pap')
                    ->join('product p', 'pap.product_id = p.id')
                    ->where('pap.attribute_type', 1);
                
                if (!empty($search)) {
                    $query = $query->where('p.name', 'like', '%' . $search . '%');
                }
                
                // 获取总数
                $total = $query->count();
                
                // 获取列表数据
                $list = $query->field([
                        'pap.id',
                        'pap.product_id', 
                        'pap.price',
                        'pap.status',
                        'pap.createtime',
                        'pap.updatetime',
                        'p.name as product_name',
                        'p.main_image',
                        'p.description'
                    ])
                    ->order('pap.id', 'desc')
                    ->limit($offset, $limit)
                    ->select();
                
                // 处理数据格式
                foreach ($list as &$item) {
                    // 格式化时间
                    $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
                    $item['updatetime'] = date('Y-m-d H:i:s', $item['updatetime']);
                    
                    // 格式化状态
                    $item['status_text'] = $item['status'] == 1 ? '上架' : '下架';
                    
                    // 格式化价格
                    $item['price'] = number_format($item['price'], 2);
                }
                
                // 返回结果
                $result = array("total" => $total, "rows" => $list);
                return json($result);
                
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => '获取权益商品数据失败: ' . $e->getMessage()]);
            }
        }
        
        return $this->view->fetch();
    }

    /**
     * 商品分类管理
     */
    public function category()
    {
        // 创建分类模型实例
        $categoryModel = new \app\admin\model\ProductCategory;
        
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            try {
                // 获取请求参数
                $page = $this->request->get('page', 1);
                $limit = $this->request->get('limit', 10);
                $search = $this->request->get('search', '');
                
                // 构建查询条件
                $query = $categoryModel;
                if (!empty($search)) {
                    $query = $query->where('name', 'like', '%' . $search . '%');
                }
                
                // 获取所有分类数据
                $allList = $query->order('parent_id', 'asc')
                    ->order('sort', 'asc')
                    ->order('id', 'asc')
                    ->select();
                
                // 分离一级分类和二级分类
                $parentCategories = [];
                $childCategories = [];
                
                foreach ($allList as $item) {
                    if ($item['parent_id'] == 0) {
                        $parentCategories[] = $item->toArray();
                    } else {
                        $childCategories[] = $item->toArray();
                    }
                }
                
                // 为有子分类的一级分类添加children字段
                foreach ($parentCategories as $key => $parent) {
                    $children = [];
                    foreach ($childCategories as $child) {
                        if ($child['parent_id'] == $parent['id']) {
                            $children[] = $child;
                        }
                    }
                    if (!empty($children)) {
                        $parentCategories[$key]['children'] = $children;
                        $parentCategories[$key]['_hasChildren'] = true;
                    } else {
                        $parentCategories[$key]['_hasChildren'] = false;
                    }
                }
                
                // 返回结果
                $result = array("total" => count($parentCategories), "rows" => $parentCategories);
                return json($result);
                
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => '获取分类数据失败: ' . $e->getMessage()]);
            }
        }
        
        // 传递状态列表到视图
        $this->view->assign("statusList", $categoryModel->getStatusList());
        return $this->view->fetch('product/category');
    }

    /**
     * 添加分类
     */
    public function categoryadd()
    {
        $categoryModel = new \app\admin\model\ProductCategory;
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 如果没有选择父级分类，设置为0（一级分类）
                if (empty($params['parent_id'])) {
                    $params['parent_id'] = 0;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $categoryModel->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取一级分类列表用于选择父级
        $parentList = $categoryModel->where('parent_id', 0)->select();
        $this->view->assign("parentList", $parentList);
        // 状态列表 - 使用数字状态值
        $statusList = ['1' => '正常', '0' => '隐藏'];
        $this->view->assign("statusList", $statusList);
        return $this->view->fetch('product/categoryadd');
    }

    /**
     * 编辑分类
     */
    public function categoryedit($ids = null)
    {
        $categoryModel = new \app\admin\model\ProductCategory;
        $row = $categoryModel->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 如果没有选择父级分类，设置为0（一级分类）
                if (empty($params['parent_id'])) {
                    $params['parent_id'] = 0;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取一级分类列表用于选择父级
        $parentList = $categoryModel->where('parent_id', 0)->select();
        $this->view->assign("parentList", $parentList);
        $this->view->assign("statusList", $categoryModel->getStatusList());
        $this->view->assign("row", $row);
        return $this->view->fetch('product/categoryedit');
    }

    /**
     * 删除分类
     */
    public function categorydel($ids = "")
    {
        $categoryModel = new \app\admin\model\ProductCategory;
        
        if ($ids) {
            $pk = $categoryModel->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $categoryModel->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    // 检查是否有子分类
                    $childCount = $categoryModel->where('parent_id', $v['id'])->count();
                    if ($childCount > 0) {
                        throw new Exception("分类【{$v['name']}】下还有子分类，不能删除");
                    }
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 显示分类数据
     */
    public function executeSqlFile()
    {
        try {
            // 读取SQL文件内容
            $sqlFile = 'd:\phpstudy_pro\WWW\fast\product_tables.sql';
            $sql = file_get_contents($sqlFile);
            
            if (!$sql) {
                echo "无法读取SQL文件";
                exit;
            }
            
            // 分割SQL语句
            $statements = explode(';', $sql);
            
            echo "<h2>执行SQL文件：</h2>";
            
            foreach ($statements as $statement) {
                $statement = trim($statement);
                if (empty($statement)) {
                    continue;
                }
                
                try {
                    Db::execute($statement);
                    echo "执行成功: " . substr($statement, 0, 50) . "...<br>";
                } catch (Exception $e) {
                    echo "执行失败: " . substr($statement, 0, 50) . "... 错误: " . $e->getMessage() . "<br>";
                }
            }
            
            echo "<h2>检查创建的数据：</h2>";
            $categories = Db::name('product_category')->select();
            echo "<pre>";
            print_r($categories);
            echo "</pre>";
            
        } catch (Exception $e) {
            echo "错误：" . $e->getMessage();
        }
        
        exit;
    }

    /**
     * 调试分类数据
     */
    public function debugCategoryData()
    {
        $categoryModel = new \app\admin\model\ProductCategory;
        
        $allCategories = $categoryModel->select();
        $parentCategories = $categoryModel->where('parent_id', 0)->select();
        
        echo "<h3>所有分类数据：</h3>";
        echo "<pre>";
        foreach ($allCategories as $category) {
            echo "ID: {$category['id']}, 名称: {$category['name']}, 父级ID: {$category['parent_id']}, 状态: {$category['status']}\n";
        }
        echo "</pre>";
        
        echo "<h3>一级分类数据：</h3>";
        echo "<pre>";
        foreach ($parentCategories as $category) {
            echo "ID: {$category['id']}, 名称: {$category['name']}\n";
        }
        echo "</pre>";
        
        exit;
    }





    /**
     * 审核拒绝
     */
    public function auditReject($ids = null)
    {
        if ($this->request->isPost()) {
            $reason = $this->request->post('reason', '');
            if (empty($reason)) {
                $this->error('请填写拒绝原因');
            }
            
            if ($ids) {
                $pk = $this->model->getPk();
                $list = $this->model->where($pk, 'in', $ids)->where('status', 2)->select();

                $count = 0;
                Db::startTrans();
                try {
                    foreach ($list as $product) {
                        // 更新商品状态为下架，并记录拒绝原因
                        $product->status = 0; // 下架
                        $product->audit_reason = $reason; // 记录拒绝原因
                        $product->save();
                        $count++;
                    }
                    Db::commit();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($count) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        // 显示拒绝原因输入框
        $this->view->assign('ids', $ids);
        return $this->view->fetch('product/audit_reject');
    }

    /**
     * 初始化分类数据（仅用于测试）
     */
    public function initCategoryData()
    {
        $categoryModel = new \app\admin\model\ProductCategory;
        
        // 先清空现有数据
        $categoryModel->where('1=1')->delete();
        
        // 创建测试数据
        $categories = [
            [
                'name' => '电子产品',
                'parent_id' => 0,
                'image' => '',
                'sort' => 1,
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time()
            ],
            [
                'name' => '服装鞋帽',
                'parent_id' => 0,
                'image' => '',
                'sort' => 2,
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time()
            ],
            [
                'name' => '家居用品',
                'parent_id' => 0,
                'image' => '',
                'sort' => 3,
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time()
            ]
        ];
        
        try {
            // 先插入一级分类
            foreach ($categories as $category) {
                $categoryModel = new \app\admin\model\ProductCategory;
                $categoryModel->save($category);
            }
            
            // 再插入二级分类
            $subCategories = [
                [
                    'name' => '手机',
                    'parent_id' => 1, // 电子产品的子分类
                    'image' => '',
                    'sort' => 1,
                    'status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ],
                [
                    'name' => '电脑',
                    'parent_id' => 1, // 电子产品的子分类
                    'image' => '',
                    'sort' => 2,
                    'status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ],
                [
                    'name' => '男装',
                    'parent_id' => 2, // 服装鞋帽的子分类
                    'image' => '',
                    'sort' => 1,
                    'status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ],
                [
                    'name' => '女装',
                    'parent_id' => 2, // 服装鞋帽的子分类
                    'image' => '',
                    'sort' => 2,
                    'status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ],
                [
                    'name' => '厨房用品',
                    'parent_id' => 3, // 家居用品的子分类
                    'image' => '',
                    'sort' => 1,
                    'status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ],
                [
                    'name' => '卧室用品',
                    'parent_id' => 3, // 家居用品的子分类
                    'image' => '',
                    'sort' => 2,
                    'status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ]
            ];
            
            foreach ($subCategories as $subCategory) {
                $categoryModel = new \app\admin\model\ProductCategory;
                $categoryModel->save($subCategory);
            }
            
            $this->success('测试数据初始化成功！创建了3个一级分类和6个二级分类');
        } catch (Exception $e) {
            $this->error('初始化失败：' . $e->getMessage());
        }
    }

    /**
     * 编辑权益商品
     */
    public function equityedit($ids = null)
    {
        if (!$ids) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        // 获取权益商品数据
        $row = Db::name('product_attribute_price')
            ->alias('pap')
            ->join('product p', 'pap.product_id = p.id')
            ->where('pap.id', $ids)
            ->where('pap.attribute_type', 1)
            ->field([
                'pap.id',
                'pap.product_id', 
                'pap.price',
                'pap.status',
                'p.name as product_name',
                'p.main_image',
                'p.description'
            ])
            ->find();
            
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    // 更新权益商品价格配置
                    $updateData = [
                        'price' => $params['price'],
                        'status' => isset($params['status']) ? $params['status'] : 1,
                        'updatetime' => time()
                    ];
                    
                    $result = Db::name('product_attribute_price')
                        ->where('id', $ids)
                        ->where('attribute_type', 1)
                        ->update($updateData);
                        
                    Db::commit();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除权益商品
     */
    public function equitydel($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $list = Db::name('product_attribute_price')
                ->where('id', 'in', $ids)
                ->where('attribute_type', 1)
                ->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $count += Db::name('product_attribute_price')
                        ->where('id', $item['id'])
                        ->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}